package com.shameit.goodqrinfomanager.ui.activity.barcode;

import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.device.ScanDevice;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

import com.codbking.widget.DatePickDialog;
import com.codbking.widget.OnSureLisener;
import com.codbking.widget.bean.DateType;
import com.shameit.goodqrinfomanager.MyApplication;
import com.shameit.goodqrinfomanager.bean.litepal.CangKu;
import com.shameit.goodqrinfomanager.bean.litepal.CangWei;
import com.shameit.goodqrinfomanager.bean.litepal.ChanPin;
import com.shameit.goodqrinfomanager.bean.litepal.HuoMa;
import com.shameit.goodqrinfomanager.bean.litepal.PiCi;
import com.shameit.goodqrinfomanager.bean.litepal.RuKu;
import com.shameit.goodqrinfomanager.bean.litepal.XiangMa;
import com.shameit.goodqrinfomanager.ui.activity.offline.OfflineManagementActivity;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import me.goldze.mvvmhabit.base.BaseModel;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class BarCodeViewModel extends BaseViewModel implements LifecycleObserver {
    private static final String TAG = "BarCodeViewModel";
    private final static String SCAN_ACTION = "scan.rcv.message";
    private String barcodeStr;
    private StringBuffer sb;
    private List<String> productList;

    public ObservableField<String> show = new ObservableField<>("");
    public ObservableField<String> cpbh = new ObservableField<>("");
    public ObservableField<String> scph = new ObservableField<>("");
    public ObservableField<String> bzsl = new ObservableField<>("");
    public ObservableField<String> scrq = new ObservableField<>("");
    public ObservableField<String> xiangma = new ObservableField<>("");
    public ObservableField<String> xiaoma = new ObservableField<>("");
    public ObservableField<String> cwbh = new ObservableField<>("");
    public ObservableField<Boolean> hasFocus = new ObservableField<>(false);
    public ObservableField<String> cpmc = new ObservableField<>("");



    private ScanDevice sm;

    public BarCodeViewModel(@NonNull Application application) {
        super(application);
        sb = new StringBuffer();
        productList = new ArrayList<>();
    }

    public BarCodeViewModel(@NonNull Application application, BaseModel model) {
        super(application, model);
        sb = new StringBuffer();
        productList = new ArrayList<>();
    }

    public BindingCommand gotoOffline = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startActivity(OfflineManagementActivity.class);
        }
    });


    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            byte[] barocode = intent.getByteArrayExtra("barocode");
            int barocodelen = intent.getIntExtra("length", 0);
            byte temp = intent.getByteExtra("barcodeType", (byte) 0);
            byte[] aimid = intent.getByteArrayExtra("aimid");
            barcodeStr = new String(barocode, 0, barocodelen);
            if (hasFocus.get()) {
                xiangma.set(barcodeStr);
            } else {
                if (!bzsl.get().isEmpty()) {
                    xiaoma.set(barcodeStr);
                    if (productList.size() >= Integer.parseInt(bzsl.get())) {
                        ToastUtils.showShort("包装数量达上限");
                    } else {
                        productList.add(barcodeStr);
                        sb.append(productList.size() + ":" + barcodeStr + "\n");
                        show.set(sb.toString());
                    }
                } else {
                    //ToastUtils.showShort("请输入包装数量");
                }
            }
            sm.stopScan();
//            int mode = sm.getScanLaserMode();
//            Log.d(TAG, "onReceive: mode:" + mode);
}
    };

    public BindingCommand startOneScan = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (bzsl.get().length() > 0) {
                sm.stopScan();
                sm.openScan();
                sm.setScanLaserMode(8);
                sm.startScan();
            } else {
                ToastUtils.showShort("请输入包装数量");
            }
        }
    });

    public BindingCommand startContinueScan = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (bzsl.get().length() > 0) {
                sm.stopScan();
                sm.openScan();
                sm.setScanLaserMode(4);
                sm.startScan();
            } else {
                ToastUtils.showShort("请输入包装数量");
            }
        }
    });

    private boolean checkIsNull(){
        boolean isNull = false;
        //if (scph.get().length()>0&&scrq.get().length()>0&&xiangma.get().length()>0&&xiaoma.get().length()>0){
        if (scph.get().length()>00&&xiangma.get().length()>0&&xiaoma.get().length()>0){
            isNull=true;
        }
        return isNull;
    }

    public BindingCommand save = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (checkIsNull()) {
                savePici();
                saveXiangma();
                saveHuoma();
                saveRuku();
                ToastUtils.showShortSafe("保存成功");
            } else {
                ToastUtils.showShortSafe("资料不全");
            }
        }
    });

    private void savePici(){
        int danCode = SPUtils.getInstance().getInt(BarCodeManagementActivity.danCode);
        PiCi piCi = new PiCi();
        piCi.setCode(String.valueOf(danCode));
        piCi.setOperator(MyApplication.loginUser.getUsername());
        piCi.save();
    }

    private void saveXiangma(){
        int danCode = SPUtils.getInstance().getInt(BarCodeManagementActivity.danCode);
        XiangMa xm = new XiangMa();
        xm.setCode(xiangma.get());
        xm.setPiciCode(String.valueOf(danCode));
        xm.setOperator(MyApplication.loginUser.getUsername());
        //xm.setOperatorTime(MyApplication.yyHHMMddhhmmss.format(new Date()));
        xm.save();
    }

    private void saveHuoma(){
        if (productList!=null&&productList.size()>0){
            for(String one:productList){
                HuoMa huoMa = new HuoMa();
                huoMa.setCode(one);
                huoMa.setChanpinCode(cpbh.get());
                huoMa.setOperator(MyApplication.loginUser.getUsername());
                huoMa.setOperatorTime(scrq.get());
                huoMa.setXiangCode(xiangma.get());
                huoMa.save();
            }
        }
    }

    private void saveRuku(){
        //用户编号 暂为空
        RuKu ruKu = new RuKu();
        ruKu.setCangweiCode(cwbh.get());
        ruKu.setXiangCode(xiangma.get());
        ruKu.setOperator("unknow");
        ruKu.setOperatorTime(MyApplication.yyHHMMddhhmmss.format(new Date()));
        ruKu.setUserCode(MyApplication.loginUser.getUsername());
        ruKu.save();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void onCreate() {
        super.onCreate();
        sm = new ScanDevice();
        sm.setOutScanMode(0);//启动就是广播模式
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void onResume(){
        Log.d(TAG, "onResume: ");
        IntentFilter filter = new IntentFilter();
        filter.addAction(SCAN_ACTION);
        getApplication().registerReceiver(mScanReceiver, filter);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void onPause(){
        Log.d(TAG, "onPause: ");
        getApplication().unregisterReceiver(mScanReceiver);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onStop(){
        Log.d(TAG, "onStop: ");
        sm.stopScan();
    }

    public void onDestroy(){
        Log.d(TAG, "onDestroy: ");
        if (sm != null) {
            sm.stopScan();
            sm.setScanLaserMode(8);
            sm.closeScan();
        }
    }

    public String[] loadCangkuItem(){
        List<CangKu> cangKuList = LitePal.order("warehouseNo").find(CangKu.class);
        String[] ckArr = new String[cangKuList.size()];
        for (int i = 0; i < cangKuList.size(); i++) {
            ckArr[i] = cangKuList.get(i).getWarehouseNo();
        }
        return ckArr;
    }

    public String[] loadCangweiItem(String cangkucode){
        List<CangWei> cangWeiList = LitePal.where("warehouseNo = ? ", cangkucode).order("placeNo").find(CangWei.class);
        String[] cwArr = new String[cangWeiList.size()];
        for (int i = 0; i < cangWeiList.size(); i++) {
            cwArr[i] = cangWeiList.get(i).getPlaceNo();
        }
        return cwArr;
    }

    public String[] loadChanpinItem(){
        List<ChanPin> cangKuList = LitePal.order("productCode").find(ChanPin.class);
        String[] ckArr = new String[cangKuList.size()];
        for (int i = 0; i < cangKuList.size(); i++) {
            ckArr[i] = cangKuList.get(i).getProductCode();
        }
        return ckArr;
    }

    public String loadChanpinName(String code){
        List<ChanPin> names = LitePal.where("productCode = ?", code).find(ChanPin.class);
        ChanPin chanPin = names.get(0);
        return chanPin.getProductName();
    }

}
